package com.corechina.apex_osswords.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.corechina.apex_osswords.domain.dto.TokenNeedFieldDto;
import com.corechina.apex_osswords.domain.entity.SysUserToken;

import java.util.Date;

public class JwtUtil {
    /**
     * 过期时间24小时
     */
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
    /**
     * 校验token是否正确
     * @param sysUserToken
     * @return 是否正确
     */
    public static boolean verify(SysUserToken sysUserToken) {
        String token = sysUserToken.getToken();
        Integer userId = sysUserToken.getUserId();
        String secret = sysUserToken.getSecret();
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("userId", userId)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static Long getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);

            return jwt.getClaim("userId").asLong();

        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名
     * @param tokenNeedFieldDto 登录人信息
     * @return 加密的token
     */
    public static String sign(TokenNeedFieldDto tokenNeedFieldDto) {
        Integer userId = tokenNeedFieldDto.getId();
        String secret = tokenNeedFieldDto.getSecret();
        //生成签发人
        String subject = tokenNeedFieldDto.getName();
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create()
                .withClaim("userId", userId)
                .withSubject(subject)
                .withExpiresAt(date)
                .sign(algorithm);
    }
}
